import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders


class sendEmail(object):
    def __init__(self, mail_user, mail_password, mail_host):
        self.mail_user = mail_user
        self.mail_password = mail_password
        self.mail_host = mail_host

    # 发送邮件
    def send_Email(self, receiver_list, mail_title, filename):
        sender = self.mail_user + '<' + self.mail_user + '@' + self.mail_host[5:] + '>'  # 拼接邮箱地址

        msg = MIMEMultipart()
        # 邮件附件读取
        att = MIMEBase('application', 'x-xz')
        att.set_payload(open(filename, 'rb').read())
        encoders.encode_base64(att)
        att.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(att)
        # 邮件正文内容读取（目前只能读txt中的内容展示在正文中）
        fp = open(filename)
        msg.attach(MIMEText(fp.read(), _charset="utf_8"))
        fp.close()

        # 邮件头
        msg['Subject'] = mail_title
        msg['From'] = sender
        msg['To'] = ";".join(receiver_list)
        # 邮件发送
        try:
            send_smtp = smtplib.SMTP()
            send_smtp.connect(self.mail_host)  # 连接smtp服务器
            send_smtp.login(self.mail_user, self.mail_password)  # 登录
            send_smtp.sendmail(sender, receiver_list, msg.as_string())  # 发送邮件
            send_smtp.close()
            return print('成功')
        except Exception as e:
            print('失败')
            print(str(e))


if __name__ == '__main__':
    # 邮箱服务器地址、用户名、密码
    host = 'smtp.126.com'
    user = 'yywonne'
    password = '09Yang09jia09yu'
    # 文件、标题、收件人名单
    file = 'test.txt'  # D:\\file\\python\\goodstudy\\report.xlsx
    title = '邮件标题'
    receiver = ['769765296@qq.com']
    s = sendEmail(user, password, host)
    s.send_Email(receiver, title, file)
